package com.jiayan.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jiayan.constants.OrderStatus;
import com.jiayan.mapper.EbOrderDtMapper;
import com.jiayan.mapper.EbOrderMapper;
import com.jiayan.mapper.EbProductMapper;
import com.jiayan.model.EbOrder;
import com.jiayan.model.EbOrderDetail;
import com.jiayan.model.EbProduct;
import com.jiayan.model.EbUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Service
public class CartService {
    @Resource
    private EbProductMapper ebProductMapper;

    @Resource
    private EbOrderMapper ebOrderMapper;

    @Resource
    private EbOrderDtMapper ebOrderDtMapper;

    public boolean addCar(Integer Pid, HttpServletRequest request) {
        EbProduct ebProduct = ebProductMapper.selectById(Pid);
        if(ebProduct == null){
            return false;
        }
        HttpSession car = request.getSession();

        Set<EbProduct> productList = (Set<EbProduct>) car.getAttribute("car");
        if(productList == null){
            productList = new HashSet<>();
        }
        for(EbProduct old : productList){
            if(old.equals(ebProduct)){
                ebProduct.setCount(old.getCount()+1);//商品数量累加
                productList.remove(old);
                break;
            }
        }
        BigDecimal currAmount = new BigDecimal("0.00");
        ebProduct.setAmount(currAmount.add(ebProduct.getEpPrice().multiply(new BigDecimal(ebProduct.getCount()+""))));//设置商品总价
        productList.add(ebProduct);
        car.setAttribute("car",productList);

        return true;
    }

    public boolean changeNum(Integer epId, BigDecimal amount, Integer newNum, HttpServletRequest request) {
        EbProduct ebProduct = ebProductMapper.selectById(epId);
        if(ebProduct == null){
            return false;
        }
        HttpSession car = request.getSession();
        Set<EbProduct> productList = (Set<EbProduct>) car.getAttribute("car");
        for(EbProduct old :productList){
            if(old.equals(ebProduct)){
                ebProduct.setCount(newNum);
                productList.remove(old);
                break;
            }
        }
        BigDecimal currAmount = new BigDecimal("0.00");
        ebProduct.setAmount(currAmount.add(amount));//重置商品总金额
        productList.add(ebProduct);
        car.setAttribute("car",productList);
        return true;
    }

    @Transactional
    public boolean createOrder(HttpServletRequest request) {
        Set<EbProduct> productSet = (Set<EbProduct>) request.getSession().getAttribute("car");
        for(EbProduct pro: productSet){
            EbProduct wareEbProduct = ebProductMapper.selectById(pro.getEpId());
            wareEbProduct.setEpStock(wareEbProduct.getEpStock()-pro.getCount());
            int reduceStockResult = ebProductMapper.update(
                    wareEbProduct,new UpdateWrapper<EbProduct>().eq("ep_id",pro.getEpId()));
            if(reduceStockResult<=0){
                throw new RuntimeException("扣减库存失败");
            }
        }
        BigDecimal amount = new BigDecimal("0.00");
        for(EbProduct ebProduct: productSet){
            amount.add(ebProduct.getEpPrice().multiply(new BigDecimal(ebProduct.getCount())));
        }
        EbOrder ebOrder = new EbOrder();
        ebOrder.setEoCreateTime(new Date());
        ebOrder.setEoCost(amount);
        ebOrder.setEoStatus(OrderStatus.ORDER_CREATED.getCode());
        EbUser user = (EbUser) request.getSession().getAttribute("user");
        if(user == null){
            throw new RuntimeException("下单失败，发货地址不能为空");
        }
        ebOrder.setEoUserAddress(user.getEuAddress());
        ebOrder.setEoUserId(user.getEuUserId());
        ebOrder.setEoUserName(user.getEuUserName());
        ebOrder.setEoType(1);

        int insertResult1 = ebOrderMapper.insert(ebOrder);
        if(insertResult1<=0){
            throw new RuntimeException("创建订单失败！");
        }

        for(EbProduct ebProduct:productSet){
            EbOrderDetail orderDetail = new EbOrderDetail();
            amount = new BigDecimal("0.00");
            orderDetail.setEodCost(amount.add(ebProduct.getEpPrice().multiply(new BigDecimal(ebProduct.getCount()))));
            orderDetail.setEoId(ebOrder.getEoId());
            orderDetail.setEodQuantity(ebProduct.getCount());
            orderDetail.setEpId(ebProduct.getEpId());

            int insertResult2 = ebOrderDtMapper.insert(orderDetail);
            System.out.println("完成对orderDetail表的插入");
            if(insertResult2<=0){
                throw new RuntimeException("创建订单详情失败！");
            }
        }
        request.getSession().removeAttribute("car");
        return false;
    }
}
